package com.cloud.aopAfter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用后置通知模拟出Aop实现原理
 */
@Component
@Slf4j
public class AsyncPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 1.判断类上是否有加上AopAsync
        AopAsync mayiktAsync = bean.getClass().getDeclaredAnnotation(AopAsync.class);
        // 2.如果类上有加上mayiktAsync 走cglib代理 采用异步执行方法
        if (mayiktAsync == null) {
            return bean;
        }
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(bean.getClass());
        enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        log.info("执行AopAsync前");
                        methodProxy.invokeSuper(o, objects);// 执行目标方法
                        log.info("执行AopAsync后");
                    } catch (Throwable throwable) {

                    }
                }
            });
            return null;
        });

        return enhancer.create();
    }
}
